package com.example.mobifin_busticket.views.activities;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

import com.example.mobifin_busticket.AppData;
import com.example.mobifin_busticket.R;
import com.example.mobifin_busticket.Util;
import com.example.mobifin_busticket.R.drawable;
import com.example.mobifin_busticket.R.id;
import com.example.mobifin_busticket.R.layout;
import com.example.mobifin_busticket.R.string;
import com.example.mobifin_busticket.controller.callbacks.ParseListner;
import com.example.mobifin_busticket.controller.callbacks.ResponseListener;
import com.example.mobifin_busticket.controller.databasemanager.DatabaseManager;
import com.example.mobifin_busticket.models.SeatDetailsModel;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.LinearLayout.LayoutParams;

@SuppressLint("ResourceAsColor")
public class SelectBusSeatActivity extends MobifinActivity implements
		OnClickListener {
	TextView txtfare, txtSeatName;
	Button btn_goBack, btn_lower, btn_upper, btn_done;
	ArrayList<SeatDetailsModel> seatList = null;
	SeatDetailsModel seatModel;
	Collection<SeatDetailsModel> sortSeat;
	ToggleButton seatButton = null, sleeperButton = null;
	LinearLayout ll_dynamivButton, ll_seat, ll_sleeperSeat, ll_btn, llError,
			llChildError;
	String strupperLower = "Lower";
	int flag = 1;
	Multimap<Integer, SeatDetailsModel> upperSeatLayout, lowerSeatLayout;
	ArrayList<Integer> fareList;
	ArrayList<String> seatName, lowerUpperseatLayout;
	ArrayList<String> lseatList;
	String fare;
	StringBuffer sb = new StringBuffer();
	String SelectedBoarding, busId, bPoint;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_bus_seat);
		fareList = new ArrayList<Integer>();
		seatName = new ArrayList<String>();
		lseatList = new ArrayList<String>();
		busId = getIntent().getStringExtra("Busid");
		seatName = getIntent().getStringArrayListExtra("seatNameList");
		System.out.println("Bus id in main seat layout:" + busId);

		txtfare = (TextView) findViewById(R.id.txt_fare);
		txtSeatName = (TextView) findViewById(R.id.txt_slctSeatName);
		btn_goBack = (Button) findViewById(R.id.btn_Goback);
		btn_done = (Button) findViewById(R.id.btn_done);
		btn_lower = (Button) findViewById(R.id.btn_lower);
		btn_upper = (Button) findViewById(R.id.btn_upper);
		ll_btn = (LinearLayout) findViewById(R.id.ll_bus);
		ll_seat = (LinearLayout) findViewById(R.id.ll_seatLayout);
		ll_sleeperSeat = (LinearLayout) findViewById(R.id.ll_sleeprSeat);
		llError = (LinearLayout) findViewById(R.id.llError_in_seat);
		llChildError = (LinearLayout) findViewById(R.id.llChildErr_in_seat);
		llError.setOnClickListener(this);
		btn_goBack.setOnClickListener(this);
		btn_done.setOnClickListener(this);
		btn_lower.setOnClickListener(this);
		btn_upper.setOnClickListener(this);

		lowerUpperseatLayout = new ArrayList<String>();
		seatList = AppData.SeatList;
		upperSeatLayout = getSeatLayout(seatList, 1);
		lowerSeatLayout = getSeatLayout(seatList, 0);
		if (flag == 1) {
			onClickLowerBtn();
		}
		if (upperSeatLayout.isEmpty() || lowerSeatLayout.isEmpty()) {
			ll_btn.setVisibility(View.GONE);
		} else
			ll_btn.setVisibility(View.VISIBLE);
	}

	private void drawSeatLayout(Multimap<Integer, SeatDetailsModel> seatMap) {
		// TODO Auto-generated method stub
		int size = seatMap.size();
		System.out.println("map size:" + size);
		Set<Integer> keys = seatMap.keySet();
		List<Integer> list = new ArrayList<Integer>(keys);
		// Collections.reverse(list);
		for (int i = getMaxValue((ArrayList<Integer>) list); i <= getMaxValue((ArrayList<Integer>) list); i--) {
			if (i == -1) {
				break;
			}
			sortSeat = seatMap.get(i);

			Collections.sort((List<SeatDetailsModel>) sortSeat,
					new Comparator<SeatDetailsModel>() {

						@Override
						public int compare(SeatDetailsModel arg0,
								SeatDetailsModel arg1) {
							// TODO Auto-generated method stub
							return (int) (arg0.getColumn() - arg1.getColumn());

						}

					});
			System.out.println("============Printing seat for Row " + i);
			System.out.println("============Row " + i + " seats size:"
					+ sortSeat.size());

			ll_seat.setPadding(10, 10, 10, 10);
			ll_dynamivButton = new LinearLayout(this);
			ll_dynamivButton.setOrientation(LinearLayout.VERTICAL);
			conditionBeforeseatlayout(i, list);
			for (final SeatDetailsModel seat : sortSeat) {
				System.out.println("no of rows" + i + "----->"
						+ seat.getColumn());
				seatButton = new ToggleButton(this);

				seatButton.setText(seat.getName());
				seatButton.setTextOff(seat.getName());
				seatButton.setTextOn(seat.getName());
				LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(
						LinearLayout.LayoutParams.WRAP_CONTENT,
						LinearLayout.LayoutParams.WRAP_CONTENT);

				parms.setMargins(5, 1, 5, 4);
				seatButton.setLayoutParams(parms);
				seatButton.setPadding(2, 2, 2, 2);
				seatButton.setEnabled(true);
				if (seat.isAvailableSeat()) {
					getAvailableSeat(seat);

				} else {
					getNonavailable(seat);
				}
				ll_dynamivButton.addView(seatButton);
				conditionforOrientation(seat);
				isAlreadySelectedSeat(seat, seatButton);
				selectSeatNameAndFare();
				seatButton
						.setOnCheckedChangeListener(new OnCheckedChangeListener() {

							@Override
							public void onCheckedChanged(
									CompoundButton buttonView, boolean isChecked) {
								// TODO Auto-generated method stub

								onButtonClick(isChecked, seat, buttonView);

							}

						});
			}
			ll_seat.addView(ll_dynamivButton);

		}
	}

	private void isAlreadySelectedSeat(SeatDetailsModel seat,
			ToggleButton seatButton) {
		System.out.println("Seat name from isAlreadyCheked:"+seatName);
		for (int i = 0; i < seatName.size(); i++) {

			if (seat.getName().toString().equals(seatName.get(i))) {
				seatButton.setChecked(true);
				Log.d("setchekcedTrue", "checked");
			}
		}
	}

	private void conditionforOrientation(SeatDetailsModel seat) {
		// TODO Auto-generated method stub
		LinearLayout.LayoutParams paramsOre = new LinearLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		paramsOre.gravity = Gravity.BOTTOM;
		ll_dynamivButton.setLayoutParams(paramsOre);
	}

	private void getNonavailable(SeatDetailsModel seat) {
		// TODO Auto-generated method stub
		LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);

		if (seat.getLength() == 1 && seat.getWidth() == 1) {
			layoutParams1.setMargins(5, 1, 5, 4);
			seatButton.setLayoutParams(layoutParams1);
			seatButton
					.setBackgroundResource(R.drawable.seat_layout_screen_nor_bkd);

		}
		if (seat.getLength() == 2 && seat.getWidth() == 1) {
			layoutParams1.setMargins(5, 5, 5, 5);
			seatButton.setLayoutParams(layoutParams1);
			seatButton
					.setBackgroundResource(R.drawable.seat_layout_screen_long_bkd);
		}
		getSleeperSeat(seat);
	}

	private void getAvailableSeat(SeatDetailsModel seat) {
		// TODO Auto-generated method stub
		LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		seatButton.setEnabled(true);
		if (seat.getLength() == 1 && seat.getWidth() == 1) {

			if (seat.isLadiesSeat()) {
				layoutParams1.setMargins(5, 1, 5, 4);
				seatButton.setLayoutParams(layoutParams1);
				seatButton
						.setBackgroundResource(R.drawable.ladies_seatbg_selecter);
			} else {
				seatButton
						.setBackgroundResource(R.drawable.button_selector_bus);
			}

		}
		if (seat.getLength() == 2 && seat.getWidth() == 1) {
			layoutParams1.setMargins(5, 5, 5, 5);
			seatButton.setLayoutParams(layoutParams1);
			if (seat.isLadiesSeat()) {

				seatButton
						.setBackgroundResource(R.drawable.ladies_sleepingseatbg_selecter);
			} else {
				seatButton
						.setBackgroundResource(R.drawable.long_seat_sleeper_width2);
			}
		}
		getSleeperSeat(seat);
	}

	private void getSleeperSeat(final SeatDetailsModel seat) {
		// TODO Auto-generated method stub
		if (seat.getWidth() == 2 && seat.getLength() == 1) {
			seatButton.setVisibility(View.GONE);
			sleeperButton = new ToggleButton(this);
			sleeperButton.setText(seat.getName());
			sleeperButton.setTextOff(seat.getName());
			sleeperButton.setTextOn(seat.getName());
			sleeperButton.setPadding(2, 2, 2, 2);

			sleeperButton.setEnabled(true);
			LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			parms.setMargins(5, 5, 5, 5);

			sleeperButton.setLayoutParams(parms);
			sleeperButton.setGravity(Gravity.CENTER);
			if (seat.isAvailableSeat()) {
				if (seat.isLadiesSeat())
					sleeperButton
							.setBackgroundResource(R.drawable.seat_layout_screen_tall_lad_avl);
				else
					sleeperButton
							.setBackgroundResource(R.drawable.seat_layout_screen_tall_avl);
			} else
				sleeperButton
						.setBackgroundResource(R.drawable.seat_layout_screen_tall_bkd);

			ll_sleeperSeat.addView(sleeperButton);
			sleeperButton
					.setOnCheckedChangeListener(new OnCheckedChangeListener() {

						@Override
						public void onCheckedChanged(CompoundButton buttonView,
								boolean isChecked) {
							// TODO Auto-generated method stub
							onButtonClick(isChecked, seat, buttonView);
						}
					});
		}
	}

	private void conditionBeforeseatlayout(int i, List<Integer> list) {
		// TODO Auto-generated method stub

		Button btnForSteering = new Button(this);

		LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(30, 30);
		parms.setMargins(10, 2, 2, 5);

		btnForSteering.setLayoutParams(parms);
		btnForSteering.setBackgroundResource(R.drawable.steering_icon);
		if (strupperLower.equals("Lower")) {
			if (i == getMinValue((ArrayList<Integer>) list)) {
				ll_dynamivButton.addView(btnForSteering);
				btnForSteering.setVisibility(View.VISIBLE);
			}
		} else {
			ll_dynamivButton.addView(btnForSteering);
			btnForSteering.setVisibility(View.INVISIBLE);
		}
		if (sortSeat.isEmpty()) {
			LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.WRAP_CONTENT,
					LinearLayout.LayoutParams.WRAP_CONTENT);
			ll_dynamivButton.setLayoutParams(layoutParams1);
			Button btnForSpace = new Button(this);
			btnForSpace.setVisibility(View.INVISIBLE);
			ll_dynamivButton.addView(btnForSpace);
		}
	}

	private Multimap<Integer, SeatDetailsModel> getSeatLayout(
			ArrayList<SeatDetailsModel> seatLIst, int index) {
		Multimap<Integer, SeatDetailsModel> map = ArrayListMultimap.create();
		for (int i = 0; i < seatLIst.size(); i++) {
			if (seatLIst.get(i).getzIndex() == index) {
				map.put(seatLIst.get(i).getRow(), seatLIst.get(i));
			}
		}
		System.out.println("map:" + map.toString());
		return map;

	}

	public int getMaxValue(ArrayList<Integer> seatList) {
		Integer maxlength = seatList.get(0);
		for (int i = 0; i < seatList.size(); i++) {
			if (seatList.get(i) > maxlength) {
				maxlength = seatList.get(i);
			}
		}
		return maxlength;
	}

	public int getMinValue(ArrayList<Integer> seatList) {
		Integer minlength = seatList.get(0);
		for (int i = 0; i < seatList.size(); i++) {
			if (seatList.get(i) < minlength) {
				minlength = seatList.get(i);
			}
		}
		return minlength;
	}

	private void onButtonClick(boolean isChecked, SeatDetailsModel seat,
			CompoundButton buttonView) {
		// TODO Auto-generated method stub
		if (isChecked) {

			if (seat.isAvailableSeat()) {
				if (seatName.size() < 6 && fareList.size() < 6) {
					seatName.add(seat.getName());
					fareList.add(seat.getFare());
					lowerUpperseatLayout.add(seat.getName());
					if (seat.isLadiesSeat())
						lseatList.add("true");
					else
						lseatList.add("false");
					onsetButtonBackground(seat, buttonView);
					buttonView.setEnabled(true);
					System.out.println("fare:" + fareList);
					System.out.println("seat list:" + seatName);
					System.out.println("Isladies:" + lseatList);
				} else
					Toast.makeText(this,
							"You can select only 6 seat at a time", 1000)
							.show();

			}
		}

		else {

			fareList.remove(seat.getFare());
			seatName.remove(seat.getName());
			if (strupperLower.equals("Lower")) {
				lowerUpperseatLayout.remove(seat.getName());
			}
			if (seat.isLadiesSeat())
				lseatList.remove("true");
			else
				lseatList.remove("false");
			onchangeButtonBackground(seat, buttonView);
			System.out.println("new fare list:" + fareList);
			System.out.println("new seat list:" + seatName);
			System.out.println("Is ladies:" + lseatList);

		}
		selectSeatNameAndFare();
		if (fareList.isEmpty()) {
			txtfare.setText(getResources().getString(R.string.zerors));
		}
		if (seatName.isEmpty())
			txtSeatName.setText(getResources().getString(
					R.string.txt_NoSeatSlcted));

	}

	private void selectSeatNameAndFare() {
		// TODO Auto-generated method stub
		double cnt = 0;
		for (int i = 0; i < fareList.size(); i++) {
			cnt = cnt + fareList.get(i);
			txtfare.setText("INR:" + "" + cnt);
		}
		for (int i = 0; i < seatName.size(); i++) {
			String name = seatName.toString().replace("[", "").replace("]", "");
			txtSeatName.setText(name);

		}
	}

	private void onsetButtonBackground(SeatDetailsModel seat,
			CompoundButton buttonView) {
		// TODO Auto-generated method stub
		if (seat.getLength() == 1 && seat.getWidth() == 1) {
			buttonView
					.setBackgroundResource(R.drawable.seat_layout_screen_nor_std);
		}
		if (seat.getLength() == 2 && seat.getWidth() == 1) {
			buttonView
					.setBackgroundResource(R.drawable.seat_layout_screen_long_std);
		}
		if (seat.getWidth() == 2 && seat.getLength() == 1) {
			buttonView
					.setBackgroundResource(R.drawable.seat_layout_screen_tall_std);
		}
	}

	private void onchangeButtonBackground(SeatDetailsModel seat,
			CompoundButton buttonView) {
		// TODO Auto-generated method stub
		if (seat.getLength() == 1 && seat.getWidth() == 1) {
			if (seat.isLadiesSeat()) {
				buttonView
						.setBackgroundResource(R.drawable.seat_layout_screen_nor_lad_avl);
			} else {
				buttonView
						.setBackgroundResource(R.drawable.seat_layout_screen_nor_avl);
			}
		}
		if (seat.getLength() == 2 && seat.getWidth() == 1) {
			if (seat.getLength() == 2 && seat.getWidth() == 1) {

				if (seat.isLadiesSeat()) {

					buttonView
							.setBackgroundResource(R.drawable.seat_layout_screen_long_lad_avl);
				} else {
					buttonView
							.setBackgroundResource(R.drawable.seat_layout_screen_long_avl);
				}
			}
		}
		if (seat.getWidth() == 2 && seat.getLength() == 1) {
			if (seat.isLadiesSeat())
				buttonView
						.setBackgroundResource(R.drawable.seat_layout_screen_tall_lad_avl);
			else
				buttonView
						.setBackgroundResource(R.drawable.seat_layout_screen_tall_avl);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_Goback:
			finish();
			break;
		case R.id.btn_lower:
			onClickLowerBtn();
			System.out.println("On lowercLick:");
			break;
		case R.id.btn_upper:
			onClickUpperBtn();
			System.out.println("On uppercLick:");
			break;
		case R.id.btn_done:
			onClickbtnDone();
			System.out.println("On uppercLick:");
			break;

		case R.id.llError_in_seat:
			llError.setVisibility(View.GONE);
			break;

		default:
			break;
		}
	}

	private void onClickbtnDone() {
		// TODO Auto-generated method stub
		if (!seatName.isEmpty()) {
			AppData.fareList = fareList;
			Intent boardingIntent = new Intent(SelectBusSeatActivity.this,
					BoardingPointInfoActivity.class);
			boardingIntent.putExtra("Busid", busId);
			startActivityForResult(boardingIntent, 1);

		} else {
			Animation slide = AnimationUtils.loadAnimation(
					getApplicationContext(), R.anim.slidedown);
			int noofField = 0;
			String errorMessage = "";
			llError.setVisibility(View.VISIBLE);
			llError.startAnimation(slide);

			noofField = 2;
			errorMessage = getResources().getString(
					R.string.bus_seerchbus_forget_title)
					+ ":" + getResources().getString(R.string.plzslctSeat);
			Util.errorFieldcreationSeatselect(SelectBusSeatActivity.this,
					llChildError, noofField, errorMessage);

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == RESULT_OK) {
			String boardingPoint = data.getStringExtra("SelectBoarding");

			Intent bIntent = new Intent();
			bIntent.putExtra("retuenfarelList", txtfare.getText());
			bIntent.putExtra("retuenSeatnameList", txtSeatName.getText());
			bIntent.putStringArrayListExtra("lowerSeatLayout",
					lowerUpperseatLayout);
			bIntent.putStringArrayListExtra("LadiesSeat", lseatList);
			AppData.SeatLayout = lowerUpperseatLayout;
			bIntent.putExtra("strupperlower", strupperLower);
			bIntent.putExtra("returnBoardig", boardingPoint);
			setResult(RESULT_OK, bIntent);
			finish();
		}
	}

	@SuppressWarnings("deprecation")
	private void onClickUpperBtn() {
		// TODO Auto-generated method stub
		if (seatList != null) {
			strupperLower = "Upper";
			ll_sleeperSeat.removeAllViews();
			btn_upper.setBackgroundResource(R.drawable.right_button_active);
			btn_lower.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.left_button));
			btn_upper.setTextColor(Color.WHITE);
			btn_lower.setTextColor(Color.BLACK);
			ll_seat.removeAllViews();

			drawSeatLayout(upperSeatLayout);

		}
	}

	private void onClickLowerBtn() {
		// TODO Auto-generated method stub
		if (seatList != null) {
			ll_sleeperSeat.removeAllViews();
			strupperLower = "Lower";
			btn_lower.setBackgroundResource(R.drawable.left_button_active);
			btn_upper.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.right_button));
			btn_upper.setTextColor(Color.BLACK);
			btn_lower.setTextColor(Color.WHITE);
			ll_seat.removeAllViews();

			drawSeatLayout(lowerSeatLayout);

		}
	}

}
